# -*- coding: utf-8 -*-

import json
import unittest

import jsonpath as jsonpath
import requests as requests
from ddt import ddt, data

from app.base_case import BaseCase
from app.lib.excel.excel import Excel


@ddt
class CaseTaskFromExcel(BaseCase, unittest.TestCase):
    """
    任务测试-通过excel获取数据进行接口测试

    顺序执行：test执行的时候是按照名字来的，所以多个test要顺序执行，最好添加a、b、c、d这样的字母到方法名中

    上下文管理：BaseCase中添加了类变量context，使用的时候只需要使用self.context即可
    """

    excel_data = Excel("data_example.xls").get_sheet_data("Sheet1", 1, 2)

    def __init__(self, methodName="runTest"):
        unittest.TestCase.__init__(self, methodName)
        BaseCase.__init__(self)

    @data(*excel_data)
    def test_excel(self, excel_data):
        """通过excel表进行接口测试"""

        case_id = excel_data["case_id"]
        case_name = str(excel_data["case_name"])
        request_url = str(excel_data["request_url"])
        request_method = str(excel_data["request_method"])
        request_header = json.loads(excel_data["request_header"])
        request_param = json.loads(excel_data["request_param"])

        # 1.数据处理
        if case_id != 1:
            request_header["token"] = self.context["token"]
        if case_id == 3:
            request_param["task_id"] = self.context["task_id"]

        # 2.发起请求
        if request_method == "get":
            response = requests.get(request_url, headers=request_header, params=request_param)
            print(response.text)
        else:
            response = requests.post(request_url, headers=request_header, data=request_param)
            print(response.text)

        # 3.处理数据
        status_code = jsonpath.jsonpath(json.loads(response.text), "$..status_code")[0]
        message = jsonpath.jsonpath(json.loads(response.text), "$..message")[0]
        data = jsonpath.jsonpath(json.loads(response.text), "$..data")[0]

        # 4.断言
        self.assertEqual(status_code, 200, str(message))
        if case_id == 2:
            data_list = jsonpath.jsonpath(json.loads(response.text), "$..data")
            self.assertIsNotNone(data_list, "列表为空")

        # 5.上下文处理
        if case_id == 1:
            self.context["token"] = jsonpath.jsonpath(json.loads(response.text), "$..token")[0]
        elif case_id == 2:
            self.context["task_id"] = jsonpath.jsonpath(json.loads(response.text), "$..id")[0]


if __name__ == '__main__':
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(CaseTaskFromExcel))
    unittest.TextTestRunner(verbosity=2).run(suite)
